import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/card_info_entity.dart';
import 'package:nyh_motorcade_app/entity/energy_type_entity.dart';
import 'package:nyh_motorcade_app/styles/colors.dart';
import 'package:nyh_motorcade_app/utils/format_utils.dart';
import 'package:nyh_motorcade_app/widgets/custom_app_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:nyh_motorcade_app/widgets/custom_popup_menu_item.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:nyh_motorcade_app/widgets/text_button_with_icon.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'bind_card_controller.dart';

class BindCardPage extends StatelessWidget {
  final controller = Get.put(BindCardController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.color_background,
      appBar: CustomAppBar(
        context: context,
        title: "绑定卡",
        actions: [
          IconButton(
            onPressed: () {
              controller.goToActivateCardPage();
            },
            icon: Image.asset("images/ic_add_card.png"),
          ),
        ],
      ),
      body: GetBuilder<BindCardController>(
        builder: (controller) {
          return Column(
            children: [
              buildHeaderWidget(),
              buildListWidget(),
              buildConfirmWidget(),
            ],
          );
        },
      ),
    );
  }

  Widget buildHeaderWidget() {
    return Container(
      padding: EdgeInsets.only(left: 8.w, right: 16.w),
      height: 40.w,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextButtonWithIcon(
                onPressed: () {
                  showEnergyTypeMenu();
                },
                icon: Image.asset(controller.showEnergyTypeMenu ? "images/ic_arrow_up.png" : "images/ic_arrow_down.png"),
                label: Text(
                  controller.energyTypeName.isNotEmpty ? controller.energyTypeName : "能源类型",
                  style: TextStyle(
                    color: Colours.color_text_theme,
                    fontSize: 14.sp,
                  ),
                ),
                textIconPadding: 5.w,
                iconTextAlignment: IconTextAlignment.iconRightTextLeft,
              ),
              SizedBox(
                width: 15.w,
              ),
              TextButtonWithIcon(
                onPressed: () {
                  showCardTypeMenu();
                },
                icon: Image.asset(controller.showCardTypeMenu ? "images/ic_arrow_up.png" : "images/ic_arrow_down.png"),
                label: Text(
                  controller.cardTypeName.isNotEmpty ? controller.cardTypeName : "卡归属",
                  style: TextStyle(
                    color: Colours.color_text_theme,
                    fontSize: 14.sp,
                  ),
                ),
                textIconPadding: 5.w,
                iconTextAlignment: IconTextAlignment.iconRightTextLeft,
              ),
            ],
          ),
          Text(
            "共${controller.cardCount}条",
            style: TextStyle(
              color: Colours.color_b7b7c0,
              fontSize: 14.sp,
            ),
          )
        ],
      ),
    );
  }

  Widget buildListWidget() {
    return Expanded(
      child: MultiStateWidget(
        child: SmartRefresher(
          controller: controller.refreshController,
          enablePullDown: true,
          enablePullUp: true,
          onRefresh: controller.onRefresh,
          onLoading: controller.onLoading,
          child: ListView.builder(
            shrinkWrap: true,
            physics: BouncingScrollPhysics(),
            controller: controller.scrollController,
            itemCount: controller.cardInfoList.length,
            itemBuilder: (context, index) {
              return buildItemWidget(index);
            },
          ),
        ),
        state: controller.multiState,
        onRetry: () {
          controller.onRetry();
        },
      ),
    );
  }

  Widget buildItemWidget(int index) {
    CardInfoItem entity = controller.cardInfoList[index];
    bool isSelect = entity.isSelect ?? false;

    return Container(
      margin: EdgeInsets.only(left: 8.w, right: 16.w, bottom: 12.w),
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              entity.isSelect = !isSelect;
              controller.update();
            },
            child: Padding(
              padding: EdgeInsets.all(8.w),
              child: isSelect ? Image.asset("images/ic_selected.png") : Image.asset("images/ic_unselect.png"),
            ),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 8.w),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.w),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(10.w),
                child: Material(
                  color: Colours.color_white,
                  child: InkWell(
                    onTap: () {
                      entity.isSelect = !isSelect;
                      controller.update();
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(vertical: 13.w, horizontal: 16.w),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Expanded(
                                child: Text(
                                  entity.name ?? "",
                                  style: TextStyle(
                                    color: Colours.color_text_theme,
                                    fontSize: 16.sp,
                                    fontWeight: FontWeight.bold,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              Visibility(
                                visible: (entity.cardType ?? "").isNotEmpty,
                                child: Container(
                                  margin: EdgeInsets.only(left: 8.w),
                                  padding: EdgeInsets.only(left: 8.w, right: 8.w, bottom: 2.w),
                                  decoration: BoxDecoration(
                                    color: (entity.cardType ?? "") == Constant.OWN_CARD ? Colours.color_34c759 : Colours.color_theme,
                                    borderRadius: BorderRadius.circular(5.w),
                                    border: Border.all(
                                      width: 1.w,
                                      color: (entity.cardType ?? "") == Constant.OWN_CARD ? Colours.color_34c759 : Colours.color_theme,
                                    ),
                                  ),
                                  child: Text(
                                    entity.cardTypeName ?? "",
                                    style: TextStyle(
                                      color: Colours.color_white,
                                      fontSize: 10.sp,
                                    ),
                                  ),
                                ),
                              ),
                              Visibility(
                                visible: (entity.energyTypeName ?? "").isNotEmpty,
                                child: Container(
                                  margin: EdgeInsets.only(left: 8.w),
                                  padding: EdgeInsets.only(left: 8.w, right: 8.w, bottom: 2.w),
                                  decoration: BoxDecoration(
                                    color: Colours.color_white,
                                    borderRadius: BorderRadius.circular(5.w),
                                    border: Border.all(width: 1.w, color: Colours.color_e7e7ea),
                                  ),
                                  child: Text(
                                    entity.energyTypeName ?? "",
                                    style: TextStyle(
                                      color: Colours.color_text_theme,
                                      fontSize: 12.sp,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 5.w,
                          ),
                          Text(
                            entity.cardNumber ?? "",
                            style: TextStyle(
                              color: Colours.color_b7b7c0,
                              fontSize: 14.sp,
                            ),
                          ),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Baseline(
                                    baseline: 30.w,
                                    baselineType: TextBaseline.alphabetic,
                                    child: Text(
                                      "余额(元)",
                                      style: TextStyle(
                                        color: Colours.color_6f7082,
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    width: 8.w,
                                  ),
                                  Baseline(
                                    baseline: 30.w,
                                    baselineType: TextBaseline.alphabetic,
                                    child: Text(
                                      FormatUtils.formatMoney(entity.cardBalance),
                                      style: TextStyle(
                                        color: Colours.color_6f7082,
                                        fontSize: 14.sp,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildConfirmWidget() {
    return Visibility(
      visible: controller.cardInfoList.isNotEmpty,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 16.w),
        decoration: BoxDecoration(
          color: Colours.color_white,
          boxShadow: [
            BoxShadow(
              color: Colours.color_0f112e_95,
              offset: Offset(0.0, -2.w),
              blurRadius: 5.w,
            ),
          ],
        ),
        child: TextButton(
          onPressed: () {
            controller.onConfirm();
          },
          child: Text(
            "确定",
            style: TextStyle(
              color: Colours.color_white,
              fontSize: 16.sp,
            ),
          ),
          style: ButtonStyle(
            backgroundColor: MaterialStateProperty.resolveWith((states) {
              return controller.getSelectCardIdList().isNotEmpty ? Colours.color_theme : Colours.color_ffd599;
            }),
            overlayColor: MaterialStateProperty.resolveWith((states) {
              return controller.getSelectCardIdList().isNotEmpty ? Colours.color_theme_deep : Colours.color_ffd599;
            }),
            shape: MaterialStateProperty.all(
              RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(28.w),
              ),
            ),
            minimumSize: MaterialStateProperty.all(Size(double.infinity, 48.w)),
          ),
        ),
      ),
    );
  }

  Future<void> showEnergyTypeMenu() async {
    List<EnergyTypeEntity> list = await controller.getEnergyType();
    if (list.isEmpty) {
      return;
    }
    controller.showEnergyTypeMenu = true;
    controller.update();
    showMenu(
      context: Get.context!,
      position: RelativeRect.fromLTRB(16.w, ScreenUtil().statusBarHeight + 56 + 40.w, ScreenUtil().screenWidth, 0.w),
      items: controller.energyTypeList.asMap().keys.map((e) => CustomPopupMenuItem(e, controller.energyTypeList[e].dictdataName ?? "")).toList(),
      elevation: 5.w,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.w),
      ),
    ).then((value) {
      controller.setSelectEnergyType(value);
    });
  }

  void showCardTypeMenu() {
    if (controller.cardTypeList.isEmpty) {
      return;
    }
    controller.showCardTypeMenu = true;
    controller.update();
    showMenu(
      context: Get.context!,
      position: RelativeRect.fromLTRB(100.w, ScreenUtil().statusBarHeight + 56 + 40.w, ScreenUtil().screenWidth, 0.w),
      items: controller.cardTypeList.asMap().keys.map((e) => CustomPopupMenuItem(e, controller.cardTypeList[e].name)).toList(),
      elevation: 5.w,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10.w),
      ),
    ).then((value) {
      controller.setSelectCardType(value);
    });
  }
}
